<template>
    <div>
        <el-row>
            <el-col :span="16">
                <div class="grid-content bg-purple">
                    <el-form :inline="true" :model="queryMap" class="demo-form-inline">
                        <el-form-item label="订餐日期">
                            <el-date-picker
                                    v-model="dateRange"
                                    end-placeholder="结束日期"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    type="daterange"
                                    value-format="yyyy-MM-dd"
                                    style="width: 240px"
                            >
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="订餐状态">
                            <el-select v-model="queryMap.statusId" clearable>
                                <el-option
                                        v-for="status in statusList"
                                        :key="status.statusId"
                                        :label="status.status"
                                        :value="status.statusId"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="search">查询</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-col>
            <el-col :span="8">
                <el-button-group>
                    <el-button icon="el-icon-plus" type="primary" @click="openAddOrder">订餐</el-button>
                    <el-button icon="el-icon-edit" type="primary" @click="openEditOrder">修改</el-button>
                    <el-button icon="el-icon-delete" type="primary" @click="delOrder">删除</el-button>
                    <el-button-group>
                        <el-button icon="el-icon-more" type="primary" @click="openDetail">查看详情</el-button>
                    </el-button-group>
                </el-button-group>
            </el-col>
        </el-row>

        <el-table
                :data="tableData"
                :height="530"
                border
                stripe
                style="width: 100%"
                @selection-change="handleSelectionChange"
        >
            <el-table-column prop="orderId" type="selection"></el-table-column>
            <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
            <el-table-column label="发起人" prop="empName" width="140"></el-table-column>
            <el-table-column label="部门名称" prop="deptName" width="140"></el-table-column>
            <el-table-column label="订餐人员" prop="members" width="190"></el-table-column>
            <el-table-column label="总金额" prop="totalprice" width="140" :formatter="formatPrice" align="right"></el-table-column>
            <el-table-column label="订餐日期" prop="orderdate" width="200" align="center"></el-table-column>
            <el-table-column label="订餐备注" prop="orderNote" width="180"></el-table-column>
            <el-table-column label="订餐状态" prop="status" width="180"></el-table-column>
        </el-table>

        <el-pagination
                :current-page="queryMap.page"
                :page-size="queryMap.limit"
                :page-sizes="[10, 20, 50, 100, 200]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        ></el-pagination>
        <OrderView
            :order-form-visible.sync = "orderFormVisible"
            @orderList="getOrderList"
            :orderRequest="orderRequest"
            :is-edit="isEdit"
        ></OrderView>
        <OrderDetail
            :detailData="detailData"
            :detail-visible.sync="detailVisible"
        ></OrderDetail>

    </div>
</template>

<script>
import OrderView from "@/views/order/OrderView.vue";
import OrderDetail from "@/components/OrderDetail.vue";
export default {
    name: "OrderMain",
    components: {OrderDetail, OrderView},
    data() {
        return {
            //查询条件
            queryMap: {
                page: 1,  // 当前页码
                limit: 10, // 每页条数
                statusId:'',//订餐状态
                empId:1,//发起人id
                before:'',
                after:''
            },
            //日期范围
            dateRange:[],
            // 总条数
            total: 0,
            statusList:[], //状态列表,可以根据状态列表查询个人发起的订餐
            tableData: [], //表格数据,后端返回渲染前端表格
            // 新增表单数据
            formData: {
                /*mealId: '',
                mealName: '',
                mealImage: '',*/
                orderId:'',//订餐编号
            },
            //订单的详情信息
            detailData: {
                reviewList:[],
                mealList: [],
                statusId:''
            },
            // 详情信息显隐
            detailVisible:false,
            // 订餐表单显隐
            orderFormVisible: false,
            //标志新增还是修改,false为新增订餐
            isEdit: false,
            //复选框选中的数据
            multipleSelection: [],

            //向子组件默认传递的信息
            orderRequest: {
                order:{
                    orderId: '',
                    empId: this.$store.state.user.empId,
                    totalprice: 0,
                    orderNote: '',
                    orderdate:new Date().toISOString().substring(0, 10),
                },
                empList: [],
                mealList: [],
                submitFlag: false
            },
        }
    },
    methods: {
        // 查询所有订餐状态
        getStatusList() {
            const self = this;
            this.$http.get('statusList').then(res => {
                self.statusList = res.data;
            }).catch(error => {
                this.$message.error('查询订餐状态失败，请联系管理员')
            })
        },
        //查询
        search(){
            // 重置页面未第一页
            this.queryMap.page = 1;
            this.getOrderList();
        },
        //格式化价格,显示为两位小数
        formatPrice(row, column, cellValue, index) {
            // 使用 toFixed 方法来格式化小数，保留两位小数
            // 注意：toFixed 返回的是一个字符串
            return cellValue.toFixed(2);
        },
        // 每页条数改变，val是改变后的每页条数
        handleSizeChange(val) {
            this.queryMap.limit = val;
            this.queryMap.page = 1;
            this.getDeptList();
        },
        // 页码改变，val是修改后的页面
        handleCurrentChange(val) {
            this.queryMap.page = val;
            this.getDeptList();
        },
        //点击复选框触发,val是勾选中的数据
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        //获取个人发起订餐
        getOrderList(){
            const self = this
            if (self.dateRange == null) {
                this.dateRange=[]
            }
            this.queryMap.before = this.dateRange[0];
            this.queryMap.after = this.dateRange[1];
            this.$http.post('getEmpOrderByPage', this.queryMap).then(res => {
                self.tableData = res.data.orders
                self.total = res.data.count
                console.log(res.data.orders)
            }).catch(() => {
                this.$message.error('获取个人发起订餐信息失败，请联系管理员')
            })
        },
        //打开订餐界面
        openAddOrder(){
            //进行时间验证,如果时间不到不允许提交,设置为每天12-18点
            if (this.isWithinTimeLimit()) {
                // 清空表单
                this.orderRequest = {
                    order: {
                        orderId: '',
                        empId: this.$store.state.user.empId,
                        totalprice: 0,
                        orderNote: '',
                        orderdate: new Date().toISOString().substring(0, 10),
                    },
                    empList: [],
                    mealList: [],
                    submitFlag: false
                };
                this.orderFormVisible = true;
            } else {
                this.$message.warning("当前时间无法订餐，订餐时间为每天12:00到18:00");
            }
        },
        //打开订餐修改界面
        openEditOrder(){
            if (this.isWithinTimeLimit()) {
                //设置标志为修改
                this.isEdit = true
                //获取选中行的Id,并向后端查询订餐数据
                //查询已经订餐的员工信息,没有订餐的员工信息
                //查询订购餐品的信息,包括餐品的数量等
                const self = this
                //判断是否选中了一条数据,
                if (self.multipleSelection.length === 0) {
                    self.$message({
                        type: 'warning',
                        message: "请选择要修改的数据"
                    })
                } else if (self.multipleSelection.length > 1) {
                    this.$message({
                        type: 'warning',
                        message: "只能选择一条数据"
                    })
                } else {
                    if (this.multipleSelection[0].status === "订餐未提交") {
                        //获取选中行的主键
                        let orderId = this.multipleSelection[0].orderId;
                        this.$http.get("/getOrderDataById/" + orderId).then(res => {
                            //根据主键获取要修改的数据
                            //只能修改当天发起的订餐
                            if (res.data.order.orderdate === new Date().toISOString().substring(0, 10)) {
                                this.orderRequest.empList = res.data.empList;
                                this.orderRequest.mealList = res.data.mealList;
                                this.orderRequest.order = res.data.order;

                                this.orderFormVisible = true
                            } else {
                                self.$message.error("只能修改当天发起的的订餐")
                            }
                        }).catch(error => {
                            self.$message.error("获取员工对象失败")
                        })
                    } else {
                        this.$message({
                            type: 'warning',
                            message: "该订餐已提交,不可修改"
                        })
                    }
                }
            }else {
                this.$message.warning("当前时间无法订餐，仅限12:00到18:00");
            }
        },
        //限制订餐时间
        isWithinTimeLimit() {
            const now = new Date();
            const hours = now.getHours();
            return hours >= 12 && hours < 18;
        },
        //批量删除订单
        delOrder(){
            const self = this
            //判断是否选中了一条数据,
            if(this.multipleSelection.length ===0){
                self.$message({
                    type:'info',
                    message:"请选择要删除的数据"
                })
                return
            }
            //询问用户
            this.$confirm('确定删除该订餐吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //点击确认的回调
                //存放要删除的员工的主键
                let orderArr = [];
                //删除订单,需要限制订单删除的节点必须为已保存或者是完成流程或者是过去的订单,不然不允许删除
                for (let i = 0; i < self.multipleSelection.length; i++) {
                    if ((self.multipleSelection[i].statusId===1 ||self.multipleSelection[i].statusId===2) && self.multipleSelection[i].orderdate === new Date().toISOString().substring(0, 10)){
                        self.$message.error("删除失败,订餐已在流程中")
                        return false
                    }
                    orderArr.push(self.multipleSelection[i].orderId)
                }

                self.$http.post('delOrder',orderArr).then(res =>{
                    if (res.data==='success'){
                        self.$message({
                            type:"success",
                            message:"删除成功"
                        })
                        //刷新列表
                        self.queryMap.page=1;
                        self.getOrderList()

                    }else {
                        self.$message.error("删除失败,请重试")
                    }
                }).catch(()=>{
                    self.$message.error("删除失败,请...")
                })
            }).catch(() => {
                //点击取消的回调
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //打开订单详情
        openDetail(){
            const self = this
            //判断是否选中了一条数据,
            if (self.multipleSelection.length === 0) {
                self.$message({
                    type: 'warning',
                    message: "请选择要查看的数据"
                })
            } else if (self.multipleSelection.length > 1) {
                this.$message({
                    type: 'warning',
                    message: "只能选择一条数据"
                })
            } else {
                //获取选中行的主键
                let orderId = this.multipleSelection[0].orderId;
                this.detailVisible=true

                this.$http.get("/getOrderDetailById/" + orderId).then(res => {
                    //根据主键获取要修改的数据
                    this.detailData = res.data
                    this.detailVisible=true
                }).catch(error => {
                    self.$message.error("获取订餐失败")
                })
            }
        },
    },
    computed: {
        // 获取 empId,需要根据empId查询发起订餐记录
        empId() {
            return parseInt(this.$store.state.user.empId);
        }
    },
    created() {
        this.queryMap.empId = this.empId;
        this.getStatusList();
        this.getOrderList()
    }
}
</script>

<style scoped>

</style>